#include "tinyxml2.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <regex>

using namespace tinyxml2;
using std::ofstream;
using std::cout;
using std::cin;
using std::endl;
using std::vector;
using std::string;

//class RssItem 储存文章
class RssItem {
public:
    string m_title;
    string m_link;
    string m_description;
    string m_content;
};//end of class RssItem

//解析Rss和输出Rss
class RssReader {
public://公有成员函数
    //解析
    void parseRss(const string& filename) {
        //创建文档对象
        XMLDocument doc;
        //加载文件,只能接收char*
        doc.LoadFile(filename.c_str());
        //判断加载是否成功
        if (doc.ErrorID()) {
            cout << filename << " id failed to loading" << endl;
            return;
        }
        //查找item节点
        XMLElement* item = doc.FirstChildElement("rss")->FirstChildElement("channel")->FirstChildElement("item");
        //如果没有找到，就返回
        while (item) {
            //找到了就接收
           //创建一个RssItem对象
            RssItem my_item;
            my_item.m_title = item->FirstChildElement("title")->GetText();
            my_item.m_link = item->FirstChildElement("link")->GetText();
            my_item.m_description = item->FirstChildElement("description")->GetText();
            my_item.m_content = item->FirstChildElement("content:encoded")->GetText();
            //去除m_description和m_content_encoded中的标签
            std::regex tagRegex("<[^>]+>");
            my_item.m_description = std::regex_replace(my_item.m_description, tagRegex, "");
            my_item.m_content = std::regex_replace(my_item.m_content, tagRegex, "");
            m_items.push_back(my_item);
            item = item->NextSiblingElement("item");
        }
    }
    //输出
    void dump(const string& filename) {
        ofstream ofs(filename);
        if (!ofs) {
            cout << filename << " open is failed" << endl;
            return;
        }
        int id = 1;
        for (auto& e : m_items) {
            ofs << "<doc>" << endl;

            ofs << "\t\t<docid>" << id << "</docid>" << endl;
            ofs << "\t\t<title>" << e.m_title << "</title>" << endl;
            ofs << "\t\t<link>" << e.m_link << "</link>" << endl;
            ofs << "\t\t<description>" << e.m_description << "</description>" << endl;
            ofs << "\t\t<content>" << e.m_content << "</content>" << endl;

            ofs << "</doc>" << endl;
            id++;

        }
    }
private://私有成员函数
private://私有数据成员
    //所有文章
    vector<RssItem> m_items;

};//end of class RssReader

void test() {
    RssReader rss;
    string read_filename("coolshell.xml");
    string write_filename("pagelib.txt");
    rss.parseRss(read_filename);
    rss.dump(write_filename);
}
int main() {
    test();
    return 0;
}